package com.github.MrWub.key;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.MrWub.SWskillAPI;
import com.github.MrWub.utils.YamlConfig;

public class KeyManager {
	private static Map<String, KeyOption> option = new HashMap<String, KeyOption>();
	private static SWskillAPI plugin;
	/**
	 * 禁止使用. 请静态调用该类方法.
	 * @param plugin
	 */
	public KeyManager(SWskillAPI plugin) {
		KeyManager.plugin = plugin;
	}
	/**
	 * 若非新建KeyOption则无需调用,直接getKeyOption后修改即可.
	 * @param name 全小写名称.
	 * @param ko 
	 */
	public static void setKeyOption(String name, KeyOption ko) {
		if (option.containsKey(name)) {
			option.remove(name);
		}
		option.put(name, ko);
	}
	
	/**
	 * 得到一个玩家的KeyOption (传引用).
	 * @param name 全小写玩家名.
	 * @return 
	 */
	public static KeyOption getKeyOption(String name) {
		return option.containsKey(name)?option.get(name):null;
	}
	
	/**
	 * 保存所有的KetOption配置到SWskillAPI的config.
	 */
	public static void saveALLKeyOption() {
		YamlConfig c = plugin.getC();
		List<String> options = new ArrayList<String>();
		for (String name : option.keySet()) {
			options.add(name + "#" + option.get(name).toString());
		}
		c.set("keyoption", options);
		try {
			c.save(new File(plugin.getDataFolder(), "config.yml"));
		} catch (IOException e) {
			e.printStackTrace();
		};
	}
	
	/**
	 * 从SWskillAPI的config.yml加载所有KeyOption,
	 * 注意：会覆盖当前所有的KeyOption
	 */
	public static void loadALLKeyOption() {
		option.clear();
		YamlConfig c = plugin.getC();
		List<String> options = c.getStringList("keyoption");
		for (String i: options) {
			String[] split = i.split("#");
			option.put(split[0], KeyOption.fromString(split[1]));
		}
	}
}
